package com.tt5.services.starter

import com.tt5.services.vertx.initRedisOptions
import io.vertx.config.ConfigRetriever
import io.vertx.core.Context
import io.vertx.core.Vertx
import io.vertx.core.impl.logging.Logger
import io.vertx.core.impl.logging.LoggerFactory
import io.vertx.kotlin.config.configRetrieverOptionsOf
import io.vertx.kotlin.config.configStoreOptionsOf
import io.vertx.kotlin.core.json.jsonObjectOf
import io.vertx.kotlin.coroutines.CoroutineVerticle
import io.vertx.kotlin.coroutines.coAwait

class MainVerticle() : CoroutineVerticle() {
  val logger: Logger = LoggerFactory.getLogger(javaClass.name)
  val subDeploymentIDs = mutableListOf<String>()

  override fun init(vertx: Vertx, context: Context) {
    logger.info("starting")
    super.init(vertx, context)
  }

  override suspend fun start() {
    vertx.initRedisOptions(
      ConfigRetriever.create(
        vertx, configRetrieverOptionsOf(
          stores = listOf(
            configStoreOptionsOf(
              type = "file",
              config = jsonObjectOf(Pair("path", "conf/redis.json"))
            )
          )
        )
      ).config.coAwait()
    )
    subDeploymentIDs.add(
      vertx.deployVerticle(SharedDatabaseVerticle()).coAwait()
    )
    subDeploymentIDs.add(
      vertx.deployVerticle(HttpServerVerticle()).coAwait()
    )
    logger.info("started")
  }

  override suspend fun stop() {
    logger.info("stopped")
    subDeploymentIDs.forEach { vertx.undeploy(it).coAwait() }
    super.stop()
  }
}
